#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import tkinter as tk
from tkinter import ttk, messagebox
import time
from datetime import datetime, timedelta

class IdleWindow:
    def __init__(self, parent, game_manager):
        self.parent = parent
        self.game_manager = game_manager
        self.window = tk.Toplevel(parent)
        self.update_timer = None
        self.setup_window()
        self.create_widgets()
        self.start_update_loop()
        
    def setup_window(self):
        """设置窗口"""
        self.window.title("挂机系统")
        self.window.geometry("700x600")
        self.window.resizable(True, True)
        self.window.configure(bg='#f0f0f0')
        
        # 设置为模态窗口
        self.window.transient(self.parent)
        self.window.grab_set()
        
        # 居中显示
        self.window.geometry("+%d+%d" % (self.parent.winfo_rootx() + 50, self.parent.winfo_rooty() + 50))
        
        # 绑定关闭事件
        self.window.protocol("WM_DELETE_WINDOW", self.close_window)
        
    def create_widgets(self):
        """创建界面组件"""
        main_frame = ttk.Frame(self.window, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.window.columnconfigure(0, weight=1)
        self.window.rowconfigure(0, weight=1)
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(2, weight=1)
        
        # 标题
        title_label = ttk.Label(main_frame, text="挂机系统", font=('Arial', 14, 'bold'))
        title_label.grid(row=0, column=0, pady=(0, 10))
        
        # 当前状态框架
        self.create_status_frame(main_frame)
        
        # 挂机地点框架
        self.create_locations_frame(main_frame)
        
        # 控制按钮框架
        self.create_control_frame(main_frame)
        
        # 关闭按钮
        ttk.Button(main_frame, text="关闭", command=self.close_window).grid(row=4, column=0, pady=(10, 0))
        
    def create_status_frame(self, parent):
        """创建状态显示框架"""
        status_frame = ttk.LabelFrame(parent, text="当前状态", padding="10")
        status_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        status_frame.columnconfigure(1, weight=1)
        
        # 角色信息
        current_char = self.game_manager.get_current_character()
        char_info = f"{current_char.name} (Lv.{current_char.level} {current_char.character_class})"
        ttk.Label(status_frame, text="当前角色:", font=('Arial', 10, 'bold')).grid(row=0, column=0, sticky=tk.W, pady=2)
        ttk.Label(status_frame, text=char_info).grid(row=0, column=1, sticky=tk.W, pady=2)
        
        # 挂机状态
        ttk.Label(status_frame, text="挂机状态:", font=('Arial', 10, 'bold')).grid(row=1, column=0, sticky=tk.W, pady=2)
        self.status_label = ttk.Label(status_frame, text="未挂机")
        self.status_label.grid(row=1, column=1, sticky=tk.W, pady=2)
        
        # 挂机地点
        ttk.Label(status_frame, text="挂机地点:", font=('Arial', 10, 'bold')).grid(row=2, column=0, sticky=tk.W, pady=2)
        self.location_label = ttk.Label(status_frame, text="无")
        self.location_label.grid(row=2, column=1, sticky=tk.W, pady=2)
        
        # 挂机时间
        ttk.Label(status_frame, text="挂机时间:", font=('Arial', 10, 'bold')).grid(row=3, column=0, sticky=tk.W, pady=2)
        self.time_label = ttk.Label(status_frame, text="0h 0m 0s")
        self.time_label.grid(row=3, column=1, sticky=tk.W, pady=2)
        
        # 预计奖励
        ttk.Label(status_frame, text="预计奖励:", font=('Arial', 10, 'bold')).grid(row=4, column=0, sticky=tk.W, pady=2)
        self.reward_label = ttk.Label(status_frame, text="经验: 0")
        self.reward_label.grid(row=4, column=1, sticky=tk.W, pady=2)
        
    def create_locations_frame(self, parent):
        """创建挂机地点框架"""
        locations_frame = ttk.LabelFrame(parent, text="挂机地点", padding="10")
        locations_frame.grid(row=2, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
        locations_frame.columnconfigure(0, weight=1)
        locations_frame.rowconfigure(0, weight=1)
        
        # 创建Treeview显示地点列表
        columns = ('name', 'level_req', 'exp_multiplier', 'description')
        self.location_tree = ttk.Treeview(locations_frame, columns=columns, show='headings', height=8)
        
        # 设置列标题
        self.location_tree.heading('name', text='地点名称')
        self.location_tree.heading('level_req', text='等级要求')
        self.location_tree.heading('exp_multiplier', text='经验倍率')
        self.location_tree.heading('description', text='描述')
        
        # 设置列宽
        self.location_tree.column('name', width=120)
        self.location_tree.column('level_req', width=80)
        self.location_tree.column('exp_multiplier', width=80)
        self.location_tree.column('description', width=300)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(locations_frame, orient=tk.VERTICAL, command=self.location_tree.yview)
        self.location_tree.configure(yscrollcommand=scrollbar.set)
        
        self.location_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        # 填充地点数据
        self.populate_locations()
        
        # 绑定双击事件
        self.location_tree.bind('<Double-1>', self.on_location_double_click)
        
    def create_control_frame(self, parent):
        """创建控制按钮框架"""
        control_frame = ttk.Frame(parent)
        control_frame.grid(row=3, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 按钮
        self.start_button = ttk.Button(control_frame, text="开始挂机", command=self.start_idle)
        self.start_button.grid(row=0, column=0, padx=(0, 10))
        
        self.stop_button = ttk.Button(control_frame, text="停止挂机", command=self.stop_idle, state=tk.DISABLED)
        self.stop_button.grid(row=0, column=1, padx=(0, 10))
        
        ttk.Button(control_frame, text="收取奖励", command=self.collect_rewards).grid(row=0, column=2, padx=(0, 10))
        ttk.Button(control_frame, text="刷新状态", command=self.refresh_status).grid(row=0, column=3)
        
    def populate_locations(self):
        """填充挂机地点数据"""
        # 清空现有项目
        for item in self.location_tree.get_children():
            self.location_tree.delete(item)
            
        # 获取可用地点
        current_char = self.game_manager.get_current_character()
        locations = self.game_manager.idle_manager.get_available_locations(current_char)
        
        location_descriptions = {
            "新手村": "适合新手的安全地带，经验获取稳定",
            "森林": "野兽出没的森林，经验获取较快",
            "山洞": "危险的洞穴，经验获取更快",
            "古战场": "古老的战场遗迹，经验获取很快",
            "魔法塔": "神秘的魔法塔，经验获取极快"
        }
        
        for location in locations:
            name = location['name']
            level_req = location['min_level']
            exp_mult = f"{location['exp_multiplier']}x"
            description = location_descriptions.get(name, "")
            
            # 检查是否满足等级要求
            if location.get('available', True):
                tags = ()
            else:
                tags = ('disabled',)
                
            item = self.location_tree.insert('', 'end', values=(name, level_req, exp_mult, description), tags=tags)
            
        # 设置禁用项目的样式
        self.location_tree.tag_configure('disabled', foreground='gray')
        
    def get_selected_location(self):
        """获取选中的地点"""
        selection = self.location_tree.selection()
        if not selection:
            return None
        item = selection[0]
        values = self.location_tree.item(item, 'values')
        return values[0] if values else None
        
    def start_idle(self):
        """开始挂机"""
        location_name = self.get_selected_location()
        if not location_name:
            messagebox.showwarning("警告", "请先选择一个挂机地点！")
            return
            
        current_char = self.game_manager.get_current_character()
        
        # 检查角色状态
        if current_char.is_idle:
            messagebox.showinfo("提示", "角色已在挂机中！")
            return
            
        if current_char.is_in_battle:
            messagebox.showwarning("警告", "角色正在战斗中，无法挂机！")
            return
            
        try:
            # 检查等级要求
            locations = self.game_manager.idle_manager.get_available_locations(current_char)
            selected_location = None
            for loc in locations:
                if loc['name'] == location_name:
                    selected_location = loc
                    break
                    
            if not selected_location:
                messagebox.showerror("错误", "选择的地点不可用！")
                return
                
            if not selected_location.get('available', False):
                reason = selected_location.get('reason', '等级不足')
                messagebox.showwarning("警告", f"无法在此地点挂机：{reason}")
                return
                
            # 开始挂机
            success, message = self.game_manager.start_idle(location_name)
            if success:
                messagebox.showinfo("成功", message)
            else:
                messagebox.showerror("错误", message)
                return
            
            # 更新按钮状态
            self.start_button.config(state=tk.DISABLED)
            self.stop_button.config(state=tk.NORMAL)
            
        except Exception as e:
            messagebox.showerror("错误", f"开始挂机失败: {str(e)}")
            
    def stop_idle(self):
        """停止挂机"""
        current_char = self.game_manager.get_current_character()
        
        if not current_char.is_idle:
            messagebox.showinfo("提示", "角色未在挂机中！")
            return
            
        try:
            # 停止挂机并获取奖励
            success, message, rewards = self.game_manager.stop_idle()
            
            if not success:
                messagebox.showerror("错误", message)
                return
            
            # 显示奖励信息
            if rewards.get('exp', 0) > 0:
                reward_text = f"挂机结束！\n\n获得奖励：\n经验: +{rewards['exp']}"
                # 检查是否升级
                old_level = current_char.level
                current_char.gain_exp(rewards['exp'])
                if current_char.level > old_level:
                    level_ups = current_char.level - old_level
                    reward_text += f"\n\n恭喜升级！\n升了 {level_ups} 级"
                messagebox.showinfo("挂机结束", reward_text)
            else:
                messagebox.showinfo("挂机结束", "挂机时间太短，没有获得奖励。")
                
            # 更新按钮状态
            self.start_button.config(state=tk.NORMAL)
            self.stop_button.config(state=tk.DISABLED)
            
        except Exception as e:
            messagebox.showerror("错误", f"停止挂机失败: {str(e)}")
            
    def collect_rewards(self):
        """收取奖励（不停止挂机）"""
        current_char = self.game_manager.get_current_character()
        
        if not current_char.is_idle:
            messagebox.showinfo("提示", "角色未在挂机中！")
            return
            
        try:
            # 获取当前奖励
            rewards = self.game_manager.update_idle_rewards()
            
            if rewards and rewards.get('exp', 0) > 0:
                old_level = current_char.level
                current_char.gain_exp(rewards['exp'])
                reward_text = f"收取奖励成功！\n\n获得奖励：\n经验: +{rewards['exp']}"
                if current_char.level > old_level:
                    level_ups = current_char.level - old_level
                    reward_text += f"\n\n恭喜升级！\n升了 {level_ups} 级"
                messagebox.showinfo("收取奖励", reward_text)
                # 重置挂机开始时间
                current_char.idle_start_time = time.time()
            else:
                messagebox.showinfo("收取奖励", "当前没有可收取的奖励。")
                
        except Exception as e:
            messagebox.showerror("错误", f"收取奖励失败: {str(e)}")
            
    def refresh_status(self):
        """刷新状态显示"""
        self.update_status_display()
        
    def update_status_display(self):
        """更新状态显示"""
        current_char = self.game_manager.get_current_character()
        
        if current_char.is_idle:
            # 计算挂机时间
            idle_duration = time.time() - current_char.idle_start_time
            hours = int(idle_duration // 3600)
            minutes = int((idle_duration % 3600) // 60)
            seconds = int(idle_duration % 60)
            
            self.status_label.config(text="挂机中", foreground='green')
            self.location_label.config(text=current_char.idle_location)
            self.time_label.config(text=f"{hours}h {minutes}m {seconds}s")
            
            # 计算预计奖励
            idle_status = self.game_manager.get_idle_status()
            if idle_status:
                current_rewards = idle_status.get('current_rewards', {})
                exp_reward = current_rewards.get('exp', 0)
                self.reward_label.config(text=f"经验: {exp_reward}")
            else:
                self.reward_label.config(text="经验: 0")
                
            # 更新按钮状态
            self.start_button.config(state=tk.DISABLED)
            self.stop_button.config(state=tk.NORMAL)
        else:
            self.status_label.config(text="未挂机", foreground='red')
            self.location_label.config(text="无")
            self.time_label.config(text="0h 0m 0s")
            self.reward_label.config(text="经验: 0")
            
            # 更新按钮状态
            self.start_button.config(state=tk.NORMAL)
            self.stop_button.config(state=tk.DISABLED)
            
    def on_location_double_click(self, event):
        """双击地点时开始挂机"""
        if self.start_button['state'] == tk.NORMAL:
            self.start_idle()
            
    def start_update_loop(self):
        """启动更新循环"""
        def update_loop():
            self.update_status_display()
            self.update_timer = self.window.after(1000, update_loop)  # 每秒更新一次
            
        update_loop()
        
    def close_window(self):
        """关闭窗口"""
        if self.update_timer:
            self.window.after_cancel(self.update_timer)
        self.window.destroy()